package com.woniuxy.factory.service.imp;

import com.woniuxy.factory.entity.Order;
import com.woniuxy.factory.entity.OrderRunit;
import com.woniuxy.factory.entity.Product;
import com.woniuxy.factory.entity.ResponseResult;
import com.woniuxy.factory.mapper.OrderMapper;
import com.woniuxy.factory.mapper.OrderUnitMapper;
import com.woniuxy.factory.mapper.ProductMapper;
import com.woniuxy.factory.service.OrderUnitServic;
import com.woniuxy.factory.util.AuditType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class OrderUnitServiceImp implements OrderUnitServic {
    @Autowired
    OrderUnitMapper orderUnitMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    OrderMapper orderMapper;
    @Override
    public ResponseResult<List<OrderRunit>> getOrderUnits(String ord_id, int page, int limit) {
        //查询指定订单的订单项个数
        int count = orderUnitMapper.getCount(ord_id);
        System.out.println(count);
        //计算当前页展示的起始条数
        int home = (page-1)*limit;
        //查询指定的订单项条数
        List<OrderRunit> orderRunits = orderUnitMapper.getOrderUnits(ord_id,home,limit);
        ResponseResult<List<OrderRunit>> responseResult = new ResponseResult<List<OrderRunit>>();
        responseResult.setCode(AuditType.No_Approval);
        responseResult.setCount(count);
        responseResult.setData(orderRunits);
        return responseResult;
    }

    //新增订单项
    @Override
    public ResponseResult addOrderUnit(String ordId, String prdId, Integer orderNumber, String remark) {
        ResponseResult responseResult = new ResponseResult();
        Order order = new Order();
        order.setOrdId(ordId);
        List<Order> orders = orderMapper.selectOrder(order);
        //查看当前订单状态
        try {
            if (orders.get(0).getOrderstate() != null && orders.get(0).getOrderstate().equals("已完成")) {
                responseResult.setMsg("订单已完成，不能添加");
                return responseResult;
            }
        } catch (NullPointerException e) {
            responseResult.setMsg("该订单不存在");
            return responseResult;
        }

        Product product = new Product();
        product.setPrdId(prdId);
        //查询商品是否存在
        List<Product> products = productMapper.selectProducts(product);
        try {
            products.get(0);
        } catch (NullPointerException e) {
            responseResult.setMsg("该商品不存在");
            return responseResult;
        }

        //增加订单项
        orderUnitMapper.insertOrderUnit(ordId, prdId, orderNumber, remark);
        responseResult.setMsg("新增成功");
        return responseResult;
    }


}
